/*
 * TID.java    0.0.1   22/ott/2009
 *
 * Copyright (c) 2009 mentalsmash.org
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * The use of the Apache License does not indicate that this project is
 * affiliated with the Apache Software Foundation.
 */
package org.mentalsmash.tazio.transactions.identifiers;

import java.io.Serializable;
import java.util.UUID;

import org.mentalsmash.documentation.Concurrency;

/**
 * A <tt>TID</tt> is an instance of <i>Transaction's</i> identifier. It is
 * currently implemente using an {@link UUID}
 * 
 * @version 0.0.1 22/ott/2009
 * @author Andrea Reale <andrea.reale@gmail.com>
 * 
 * @synch this class is immutable. No synchornization concerns.
 */

@Concurrency(concurrentAccess = false, specification = "this class is immutable.")
public final class TID implements Serializable {

    private static final long serialVersionUID = -8801091721599972708L;
    public static final TID NULL_TID = new TID(UUID
	    .fromString("00000000-0000-0000-0000-00000000000"));
    private final UUID id;

    /**
     * Generates a new <tt>TID</tt> instance. The generated instance is an
     * <strong>invalid</strong> TID.
     */
    TID() {
	this.id = null;
    }

    /**
     * Generates a new <tt>TID</tt> instance, having the given UUID as beckend
     * id.
     * 
     * @param id
     *            the identifier of this TID
     */
    private TID(final UUID id) {
	this.id = id;
    }

    /**
     * Generates a new <i>Transaction Identifier</i> The identifier is
     * guaranteed to be (statistically) globally unique
     * 
     * @return a new <tt>TID</tt>
     */
    public static TID generateTID() {
	final TID tid = new TID(UUID.randomUUID());
	return tid;
    }

    @Override
    public String toString() {
	return this.id.toString();
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
	return this.id.hashCode();
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(final Object obj) {
	if (this == obj) {
	    return true;
	}
	if (obj == null) {
	    return false;
	}
	if (getClass() != obj.getClass()) {
	    return false;
	}
	final TID other = (TID) obj;
	if (this.id == null) {
	    if (other.id != null) {
		return false;
	    }
	} else if (!this.id.equals(other.id)) {
	    return false;
	}
	return true;
    }

}
